package com.example.controller;

import com.example.common.Code;
import com.example.common.Result;
import com.example.domain.Record;
import com.example.service.RecordService;
import com.example.utils.ExcelUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author luo
 * 考勤管理
 */
@RestController
@RequestMapping("/records")
public class RecordController {

    @Autowired
    private RecordService recordService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public Result selectRecord(){
        List<Record> record1 = recordService.selectAllRecord();
        String msg = record1!=null ? "" : "数据查询失败，请重试！";
        Integer code = record1 != null ? Code.GET_OK : Code.GET_ERR;
        return new Result(code,record1,msg);
    }
    @GetMapping("/{id}")
    public Result selectRecordById(@PathVariable Integer id){
        Record records = null;

        String key = "Record_ID：" +id;
        //先从redis中获取缓存数据
        records = (Record) redisTemplate.opsForValue().get(key);

        if(records != null){
            //如果存在，直接返回，无需查询数据库
            return new Result(Code.GET_OK,records,"查询成功！");
        }
        records = recordService.selectRecordById(id);
        redisTemplate.opsForValue().set(key,records,60, TimeUnit.MINUTES);

        String msg = records!=null ? "" : "数据查询失败，请重试！";
        Integer code = records != null ? Code.GET_OK : Code.GET_ERR;
        return new Result(code,records,msg);
    }

    @PostMapping("/ByName")
    public Result selectRecordByName(@RequestBody Record record){
        List<Record> record1 = recordService.selectRecordByName(record);
        String msg = record1!=null ? "" : "数据查询失败，请重试！";
        Integer code = record1 != null ? Code.GET_OK : Code.GET_ERR;
        return new Result(code,record1,msg);
    }

    @PostMapping
    public Result addRecord(@RequestBody Record record){
        int i = recordService.addRecord(record);
        String msg = i > 0 ? "" : "数据添加失败，请重试！";
        if (i > 0) {
            System.out.println("插入成功");
            return new Result(Code.INSERT_OK,i,msg);
        } else {
            System.out.println("插入失败");
            return new Result(Code.INSERT_ERR,i,msg);
        }
    }
    @PutMapping
    public Result updateRecord(@RequestBody Record record) {
        int i = recordService.updateRecord(record);
        String msg = i > 0 ? "" : "数据更新失败，请重试！";

        //删除redis中缓存
        String key = "Record_ID：" +record.getId();
        redisTemplate.delete(key);

        if (i > 0) {
            System.out.println("更新成功");
            return new Result(Code.UPDATE_OK, i, msg);
        } else {
            System.out.println("更新失败");
            return new Result(Code.UPDATE_ERR, i, msg);
        }
    }
    @GetMapping("/ByName/{name}")
    public Result updateRecordByName(@PathVariable String name) {
        int i = recordService.updateRecordByName(name);
        String msg = i > 0 ? "" : "数据更新失败，请重试！";

        if (i > 0) {
            System.out.println("更新成功");
            return new Result(Code.UPDATE_OK, i, msg);
        } else {
            System.out.println("更新失败");
            return new Result(Code.UPDATE_ERR, i, msg);
        }
    }
    @DeleteMapping("/{id}")
    public Result deleteRecord(@PathVariable Integer id){
        int i = recordService.deleteRecord(id);
        String msg = i > 0 ? "" : "数据删除失败，请重试！";

        //删除redis中缓存
        String key = "Record_ID：" +id;
        redisTemplate.delete(key);

        if (i > 0) {
            System.out.println("删除成功");
            return new Result(Code.DELETE_OK, i, msg);
        } else {
            System.out.println("删除失败");
            return new Result(Code.DELETE_OK, i, msg);
        }
    }

    /**
     * 定时删除打卡数据（利用cron表达式每月凌晨0点定时清空打卡数据）
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    public void deleteAll(){
        int i = recordService.deleteAll();
        if (i > 0) {
            System.out.println("定时删除成功");
        } else {
            System.out.println("定时删除失败");
        }
    }
    @GetMapping("/{page}/{size}")
    public Result findUserList(@PathVariable int page,@PathVariable int size) {
        PageInfo<Record> page1 = recordService.findPage(page, size);
        Integer code = page1 != null ? Code.GET_OK : Code.GET_ERR;
        String msg = page1 != null ? "" : "分页失败，请重试！";
        return new Result(code, page1, msg);
    }
    @RequestMapping("/makeExcel")
    public void makeExcel(HttpServletResponse response) throws Exception {
        //打印Excel表
        ExcelUtils.exportExcel(response, "record.xlsx", recordService.getOutputExcelProjectData());
    }
}
